#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
#include <streambuf>
#include <map>
#include <vector>
using namespace std;
extern "C" int input(char* path, vector<string> &words);
extern "C" int gen_chain_char(vector<string> words, int len, vector<string> &result,
					char head, char tail, char reject, bool enable_loop);
extern "C" void output(vector<string> result);
extern "C" int gen_chain_word(vector<string> words, int len, vector<string> &result,
					char head, char tail, char reject, bool enable_loop);
extern "C" int gen_chains_all(vector<string> words, int len, vector<string> &result);

int main(int argc, char *argv[]) {
	char type = 0;
	char head = 0;
	char tail = 0;
	char reject = 0;
	bool enable_loop = false;
	char* path;
	for(int i = 1; i < argc; i ++) {
		if(argv[i][0] == '-') {
			if(argv[i][1] != 'r' && 
				(i == argc - 1 || argv[i + 1][0] == '-')) {
				puts("parameter is missing a value");
				return -1;
			}
			if(argv[i][1] == 'h') {
				head = argv[++ i][0];
			} else if(argv[i][1] == 't') {
				tail = argv[++ i][0];
			} else if(argv[i][1] == 'j') {
				reject = argv[++ i][0];
			} else if(argv[i][1] == 'r') {
				enable_loop = true;
			} else if(argv[i][1] == 'n' || argv[i][1] == 'w' || argv[i][1] == 'c') {
				if(type != 0) {
					puts("parameters not compatible"); 
					return -1;
				}
				type = argv[i][1];
				path = argv[++ i];
			} else {
				puts("illegal parameter");
				return -1;
			}
		} else {
			puts("illegal parameter");
			return -1;
		}
	}
	vector<string> words;
	if(input(path, words)) {
		return -1;
	}
	ofstream outputFile("solution.txt");
	streambuf *old;
	old = cout.rdbuf(outputFile.rdbuf());
	if(head != 0 && head == reject) {
		return 0;
	}
	vector<string> result;
	if(type == 'n') {
		int num = gen_chains_all(words, words.size(), result);
		if(num == -1) {
			return -1;
		}
		cout << num << endl;
		output(result);
	} else if(type == 'w') {
		int num = gen_chain_word(words, words.size(), result, head, tail, reject, enable_loop);
		if(num == -1) {
			return -1;
		}
		output(result);
	} else if(type == 'c') {
		int num = gen_chain_char(words, words.size(), result, head, tail, reject, enable_loop);
		if(num == -1) {
			return -1;
		}
		output(result);
	}
	cout.rdbuf(old);
	outputFile.close();
	return 0;
}
